package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.minio.MinioProperties;
import com.atguigu.lease.web.admin.service.FileUploadService;
import io.minio.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

@Service
public class FileUploadServiceImpl implements FileUploadService {
    @Autowired
    MinioProperties minioProperties;
    @Autowired
    MinioClient minioClient;
    @Override
    public String upload(MultipartFile file) {

          try {

              //检查桶是否存在
              boolean res = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build());
               if(!res){
                      //不存在就创建新的桶
                     minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucketName()).build());

                     String policy="""
                                    {
                                      "Statement" : [ {
                                        "Action" : "s3:GetObject",
                                        "Effect" : "Allow",
                                        "Principal" : "*",
                                        "Resource" : "arn:aws:s3:::%s/*"
                                      } ],
                                      "Version" : "2012-10-17"
                                    }
                                    """.formatted(minioProperties.getBucketName());

                     minioClient.setBucketPolicy(SetBucketPolicyArgs.builder().bucket(minioProperties.getBucketName()).config(policy).build());
               }else{
                   System.out.println("exist!");
               }

               //原始的文件名字 比如 : 1.jpg
              String originalFilename = file.getOriginalFilename();

              //截取后缀名字
              String suffixName = originalFilename.substring(originalFilename.lastIndexOf("."));

              //拼接新的文件名字
               String fileName= UUID.randomUUID()+suffixName;


              //上传文件
              /*
              *  contentType: 文件的类型
              * object() 保存到桶中的文件名字
              * */
              minioClient.putObject(PutObjectArgs.builder().bucket(minioProperties.getBucketName())
                                                           .object(fileName)
                                                           .contentType(file.getContentType())
                              .stream(file.getInputStream(),file.getSize(),-1)
                       .build());


              System.out.println("上传成功");


              return  String.join("/",minioProperties.getEndpoint(),minioProperties.getBucketName(),fileName);

          }catch (Exception e){
               e.printStackTrace();
          }

        return null;
    }
}
